<template>
  <div class="app-container">
    <div class="searchStyle">
      <div class="searchStyle">
        <div>
          <el-input
            v-model="queryParams.version"
            placeholder="版本号"
            :prefix-icon="Search"
            style="width: 200px;margin-right: 15px;"
            @keyup.enter="handleQuery"
          />
        </div>
        <div>
          <el-select
            v-model="queryParams.platform"
            style="width: 200px;margin-right: 15px;"
            placeholder="平台"
            @change="handleQuery"
            clearable
          >
            <el-option label="IOS" value="IOS" />
            <el-option label="Android" value="Android" />
          </el-select>
        </div>
      </div>
      <div>
        <el-button
          type="primary"
          plain
          @click="handleAdd"
          >新建</el-button
        >
      </div>
    </div>

    <el-table v-loading="loading" :data="versionData" @selection-change="handleSelectionChange">
      <el-table-column
          label="序号"
          width="60"
          type="index"
        ></el-table-column>
      <el-table-column label="版本号" align="center" prop="version" />
      <el-table-column label="下载地址" align="center" prop="filePath" />
      <el-table-column label="移动端平台" align="center" prop="platform" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
          <span>{{ scope.row.status ? ' 正常' : ' 禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          > -->
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

     <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="settingRef" :model="form" :rules="rules" label-width="110px" label-position="top">
        <el-form-item label="版本号" prop="version ">
          <el-input v-model="form.version " />
        </el-form-item>

        <el-form-item label="移动端平台" prop="platform">
          <el-select v-model="form.platform">
            <el-option label="IOS" value="IOS" />
            <el-option label="Android" value="Android" />
          </el-select>
        </el-form-item>

        <el-form-item label="上传文件" prop="file">
          <el-upload
            class="upload-demo"
            drag
            :auto-upload="false"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="handleFileChange"
            :limit="1"
            :file-list="form.file"
            accept=".xlsx, .xls, .pdf"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              Drop file here or <em>click to upload</em>
            </div>
          </el-upload>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="rostering">
import { Calendar, Search, Share } from "@element-plus/icons-vue"
import {
  versionList,
  versionSwitch,
  uploadAppversion,
  deleteAppversion,
} from "@/api/system/appVersion"
import ShiftCalendar from '@/components/ShiftCalendar/index.vue'
import useUserStore from "@/store/modules/user"
import { deptSonUserTree } from "@/api/system/role"
import { getToken } from '@/utils/auth'

const { proxy } = getCurrentInstance()

const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/system/app/version/upload/appVersion'
const versionData = ref([])
const open = ref(false)
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const shiftCalendarRef = ref(null)
const userInfo = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptName: null,
    type: null,
  },
  rules: {
    deptId: [{ required: true, message: "排班组织不能为空", trigger: "change" }],
    responsibleBy: [{ required: true, message: "排班责任人不能为空", trigger: "change" }],
    type: [{ required: true, message: "排班类型不能为空", trigger: "change" }],
    firstTeam: [{ required: true, message: "早班人员不能为空", trigger: "change" }],
    applyDate: [{ required: true, message: "适用日期范围不能为空", trigger: "change" }],
  },
})

const { queryParams, form, rules } = toRefs(data)

// 任务状态修改
const handleStatusChange = (row) => {
  let text = row.status ? "启用" : "禁用";
  proxy.$modal.confirm('请确认是否要' + text).then(function () {
    return versionSwitch({id:row.id, status:row.status ? '正常' : '禁用'});
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status === 0 ? 1 : 0;
  });
}
const editDialog = reactive({
  title: "",
  open: false,
  form: {
    deptId: null,
    responsibleBy: null,
    type: null,
    isNoonBreak: '0',
  },
  calendarDate: new Date(),
  rules: {
    deptId: [{ required: true, message: "排班组织不能为空", trigger: "change" }],
    responsibleBy: [{ required: true, message: "排班责任人不能为空", trigger: "change" }],
    type: [{ required: true, message: "排班类型不能为空", trigger: "change" }],
  },
})

const deptOptions = ref([])
const userOptions = ref([])

// 获取下拉数据
useUserStore().getInfo().then((res)=>{
  // 获取责任人
  deptSonUserTree({deptId:res.user.dept.deptId}).then((response) => {
    if(response.code == 200) {
      deptOptions.value = [response.data]
      userOptions.value = [transformDeptTree(response.data,true)]
      userInfo.value  = response.data.userList[0];
    }
  })
})
function handlePreview(file) {
  previewImage.value = file.url || file.response?.url
  previewVisible.value = true
}
const handleRemove = (file, fileList) => {
  form.value.fileList = fileList
}

function handleFileChange(file, currentFileList) {
  form.value.fileList = currentFileList
}
/** 查询【请填写功能名称】列表 */
function getList() {
  loading.value = true
  versionList(queryParams.value).then((response) => {
    versionData.value = response.rows.map(item => ({
    ...item,
    status: item.status === "正常"
}))
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {}
  proxy.resetForm("settingRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "新增"
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["settingRef"].validate((valid) => {
     if (valid) {
      const formData = new FormData()
      formData.append('platform ', form.value.platform )
      formData.append('version ', form.value.version )
      formData.append('file', form.value.fileList[0].raw)
      uploadAppversion(formData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
     }
  })
}



/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/setting/export",
    {
      ...queryParams.value,
    },
    `setting_${new Date().getTime()}.xlsx`
  )
}

getList()



/** 修改按钮操作 */
function handleUpdate(row) {
  editDialog.form= row
  editDialog.open = true
  title.value = '编辑'
}
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('请确认是否删除该数据').then(function () {
    return deleteAppversion([row.id]);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
const editCancel = () => {
  editDialog.open = false
  reset()
}
const editSubmitForm = () => {
  proxy.$refs["editDialogFormRef"].validate((valid) => {
    if (valid) {
      let data ={
        ...editDialog.form,
      }
      data.deptId = editDialog.form.deptId[editDialog.form.deptId.length - 1]
      putSchedule(data).then((response) => {
        proxy.$modal.msgSuccess("修改成功")
        editDialog.open = false
        getList()
      })
    }
  })
}



function transformDeptTree(deptNode, isRoot = false) {
  // 1. 处理当前部门节点
  const transformedNode = {
    id: deptNode.deptId,
    label: deptNode.deptName,
    children: []
  };

  // 2. 合并用户到同层级children（优先处理用户）
  if (deptNode.userList?.length > 0) {
    transformedNode.children.push(
      ...deptNode.userList.map(user => {
       return {
        id: user.userId,
        name: user.userName,
        label: `${user.nickName} (${user.userName})`,
        isUser: true
      }})
    );
  }

  // 3. 递归处理子部门
  if (deptNode.children?.length > 0) {
    transformedNode.children.push(
      ...deptNode.children.map(child => transformDeptTree(child))
    );
  }

  // 4. 根节点特殊处理：将第一个子元素移到最前
  if (isRoot && transformedNode.children.length > 0) {
    const firstChild = transformedNode.children.shift();
    transformedNode.children.unshift(firstChild); // 显式确保顺序
  }

  // 5. 处理空children
  if (transformedNode.children.length === 0) {
    delete transformedNode.children;
  }

  return transformedNode;
}

</script>
<style scoped lang="scss">
.searchStyle {
  display: flex;
  margin-bottom: 10px;
}
</style>
<style>
.rosteringEditDialog .h5{
  margin-top: 20px;
  font-size: 16px;
  font-weight: bold;
}
.rosteringEditDialog .h51{
  margin-top: 0;
  margin-bottom: 20px;
}

</style>

